﻿using System;
using System.Collections.Generic;
using System.Text;
using Boomerang.Common.Configuration;
using System.Threading;
using Boomerang.Common.Crm;
using Microsoft.Crm.Sdk;
using Boomerang.Common.Sms;
using System.Diagnostics;

namespace Boomerang.Service.Threading
{
    public class WorkerThreadSend : WorkerThreadBase
    {

        public WorkerThreadSend(Organization org, ManualResetEvent e, int index)
            : base(org, e, index)
        { }

        protected override void DoWork()
        {
            List<BusinessEntity> messages = new List<BusinessEntity>();

            Trace.TraceInformation("Sending outbound messages");
            try
            {
                messages = crmDataSource.RetrievePendingSms();
            }
            catch (Exception ex)
            {
                Trace.TraceError("Error retieving pending Sms from CRM. {0} \n {1}", ex.Message, ex.StackTrace);
            }

            Trace.TraceInformation("Processing {0} outbound sms", messages.Count);

            //Process Messages
            foreach (CrmSms sms in messages)
            {               
                Trace.TraceInformation("Sending outbound sms guid={0}", sms.CrmSmsId);
                try
                {

                    smsDataSource.SendSms(sms.MobilePhone, sms.TextMessage, sms.CrmSmsId.ToString());

                    sms.DeliveryStatus = CrmSmsDeliveryStatus.Sent;
                    sms.DateProcessed = DateTime.Now.ToUniversalTime();
                    Trace.TraceInformation("Sent outbound sms guid={0}", sms.CrmSmsId);
                    crmDataSource.Update(sms);
                    Trace.TraceInformation("Updated outbound sms status to sent guid={0}", sms.CrmSmsId);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("Error at outbound sms guid={0}. {1} \n {2}", sms.CrmSmsId,ex.Message,ex.StackTrace);
                    continue;
                }
            }
            Trace.TraceInformation("Finish send outbound messages");
        }
    }
}
